package com.xiaoxin.experience.service.hls;

import com.xiaoxin.experience.service.hls.common.HlsFactory;
import com.xiaoxin.experience.service.hls.common.HlsTask;
import com.xiaoxin.experience.service.hls.common.TaskStatus;
import com.xiaoxin.experience.service.hls.properties.HlsProperties;
import com.xiaoxin.experience.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author xiaoxin
 */
@Slf4j
@Service
public class HlsService
{

    @Resource
    HlsProperties hlsProperties;

    private static final Map<String,HlsTask> HLS_TASK_MAP = new ConcurrentHashMap<>();

    public void download(String hlsDownloadUrl)
    {
        String saveDir = hlsProperties.getSaveDir();
        String hlsFileName = RandomUtil.randomString(8);
        HlsTask hlsTask = new HlsTask(hlsFileName, saveDir, hlsDownloadUrl);
        download(hlsTask);
    }

    public void download(HlsTask hlsTask)
    {
        if (Objects.isNull(hlsTask) || HLS_TASK_MAP.containsKey(hlsTask.getTaskId()))
        {
            return;
        }
        HlsFactory.getInstance().init(hlsProperties);
        HLS_TASK_MAP.put(hlsTask.getTaskId(),hlsTask);
        ThreadUtil.postDelay(()->
        {
            long currentTimeMillis = System.currentTimeMillis();
            hlsTask.setStatus(TaskStatus.RUNNING);
            HlsFactory.getInstance().download(hlsTask);
            hlsTask.setSpendTime(DownloadUtil.consumeTime(currentTimeMillis));
        },1000);
    }

    public void retry(String taskId)
    {
        HlsTask hlsTask = HLS_TASK_MAP.get(taskId);
        if (Objects.nonNull(hlsTask) && hlsTask.getStatus() == TaskStatus.ERROR)
        {
            HlsTask remove = HLS_TASK_MAP.remove(taskId);
            download(remove);
        }
    }

    public void remove(String taskId, boolean removeFile)
    {
        if (StringUtil.isNotBlank(taskId))
        {
            HlsTask remove = HLS_TASK_MAP.remove(taskId);
            if (Objects.nonNull(remove))
            {
                remove.setRemoved(true);
                String savePath = remove.getFileSavePath();
                if (removeFile && StringUtil.isNotBlank(savePath))
                {
                    FileUtil.deleteFile(new File(savePath));
                }
            }
        }
    }

    public List<HlsTask> getAllHlsTasks()
    {
        Collection<HlsTask> values = HLS_TASK_MAP.values();

        return values.stream().sorted(Comparator.comparingInt(HlsTask::getStatus)).collect(Collectors.toList());
    }
}
